import React from 'react'
import { Cascader } from 'antd'
import { SERVER_ADMIN } from 'configs/service'
import axios from 'axios'
import { checkres } from 'utils'

export default function SelectDeviceCategory(props) {
  const { value, ...restProps } = props

  const [options, setOptions] = React.useState([])

  React.useEffect(() => {
    axios
      .post(
        '/dict/list',
        {
          pageIndex: 1,
          pageSize: 500,
          code: 'mec_device',
        },
        { baseURL: SERVER_ADMIN }
      )
      .then(res => {
        if (!checkres(res)) return
        const options = res.data.data.list
          .filter(v => v.code.startsWith('mec_device'))
          .map(v => ({ value: v.dictId, label: v.name, isLeaf: false }))
        setOptions(options)
      })
  }, [])

  React.useEffect(() => {
    if (!value) return
    const [v0, v1] = value
    if (v0 && v1) {
      const targetOption = options.find(v => v.value === v0)
      if (targetOption && !targetOption.children) loadData([targetOption])
    }
  }, [options, value])

  function loadData(selectedOptions) {
    const targetOption = selectedOptions.slice(-1)[0]
    targetOption.loading = true
    axios
      .post(
        '/dict/detailList',
        {
          pageIndex: 1,
          pageSize: 500,
          dictId: String(targetOption.value),
        },
        { baseURL: SERVER_ADMIN }
      )
      .then(res => {
        targetOption.loading = false
        if (!checkres(res)) return
        targetOption.children = res.data.data.list.map(v => ({
          value: v.dictId,
          label: v.name,
        }))
        setOptions(v => [...v])
      })
  }

  return (
    <Cascader
      value={value}
      options={options}
      loadData={loadData}
      {...restProps}
    ></Cascader>
  )
}
